package com.eduagent.xwqeduagent.controller;

import com.eduagent.xwqeduagent.service.FileService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

/**
 * 通用文件上传控制器
 */
@RestController
@RequestMapping("/api/files")
@Slf4j
public class FileController {

    @Autowired
    private FileService fileService;

    /**
     * 上传文件到指定目录
     *
     * @param file 文件
     * @param directory 目录（可选，默认为common）
     * @return 文件URL
     */
    @PostMapping("/upload")
    public ResponseEntity<Map<String, String>> uploadFile(
            @RequestParam("file") MultipartFile file,
            @RequestParam(value = "directory", defaultValue = "common") String directory) {
        
        try {
            if (file.isEmpty()) {
                return ResponseEntity.badRequest().body(createResponse("error", "文件为空"));
            }
            
            String fileUrl = fileService.uploadFile(file, directory);
            return ResponseEntity.ok(createResponse("url", fileUrl));
        } catch (Exception e) {
            log.error("文件上传失败: {}", e.getMessage(), e);
            return ResponseEntity.badRequest().body(createResponse("error", "文件上传失败: " + e.getMessage()));
        }
    }
    
    /**
     * 上传文本内容为文件
     *
     * @param content 文件内容
     * @param fileName 文件名
     * @param directory 目录（可选，默认为common）
     * @return 文件URL
     */
    @PostMapping("/upload/content")
    public ResponseEntity<Map<String, String>> uploadContent(
            @RequestParam("content") String content,
            @RequestParam("fileName") String fileName,
            @RequestParam(value = "directory", defaultValue = "common") String directory) {
        
        try {
            String fileUrl = fileService.uploadContent(content, fileName, directory);
            return ResponseEntity.ok(createResponse("url", fileUrl));
        } catch (Exception e) {
            log.error("内容上传失败: {}", e.getMessage(), e);
            return ResponseEntity.badRequest().body(createResponse("error", "内容上传失败: " + e.getMessage()));
        }
    }

    /**
     * 删除文件
     *
     * @param fileUrl 文件URL
     * @return 删除结果
     */
    @DeleteMapping("/delete")
    public ResponseEntity<Map<String, String>> deleteFile(@RequestParam("fileUrl") String fileUrl) {
        try {
            boolean success = fileService.deleteFile(fileUrl);
            if (success) {
                return ResponseEntity.ok(createResponse("message", "文件删除成功"));
            } else {
                return ResponseEntity.badRequest().body(createResponse("error", "文件删除失败"));
            }
        } catch (Exception e) {
            log.error("文件删除失败: {}", e.getMessage(), e);
            return ResponseEntity.badRequest().body(createResponse("error", "文件删除失败: " + e.getMessage()));
        }
    }

    /**
     * 检查文件是否存在
     *
     * @param fileUrl 文件URL
     * @return 检查结果
     */
    @GetMapping("/exists")
    public ResponseEntity<Map<String, Object>> checkFileExists(@RequestParam("fileUrl") String fileUrl) {
        try {
            boolean exists = fileService.doesFileExist(fileUrl);
            
            Map<String, Object> response = new HashMap<>();
            response.put("exists", exists);
            response.put("url", fileUrl);
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("检查文件失败: {}", e.getMessage(), e);
            Map<String, Object> response = new HashMap<>();
            response.put("error", "检查文件失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }
    
    /**
     * 获取文件内容
     *
     * @param fileUrl 文件URL
     * @return 文件内容
     */
    @GetMapping("/content")
    public ResponseEntity<String> getFileContent(@RequestParam("fileUrl") String fileUrl) {
        try {
            String content = fileService.getFileContent(fileUrl);
            return ResponseEntity.ok(content);
        } catch (Exception e) {
            log.error("获取文件内容失败: {}", e.getMessage(), e);
            return ResponseEntity.badRequest().body("获取文件内容失败: " + e.getMessage());
        }
    }
    
    /**
     * 下载文件
     *
     * @param fileUrl 文件URL
     * @return 文件下载
     */
    @GetMapping("/download")
    public ResponseEntity<FileSystemResource> downloadFile(@RequestParam("fileUrl") String fileUrl) {
        try {
            File tempFile = fileService.downloadToTemp(fileUrl);
            
            // 从URL提取文件名
            String fileName = fileUrl.substring(fileUrl.lastIndexOf("/") + 1);
            
            return ResponseEntity.ok()
                    .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + 
                            URLEncoder.encode(fileName, StandardCharsets.UTF_8.toString()))
                    .contentType(MediaType.APPLICATION_OCTET_STREAM)
                    .body(new FileSystemResource(tempFile));
        } catch (Exception e) {
            log.error("文件下载失败: {}", e.getMessage(), e);
            return ResponseEntity.badRequest().body(null);
        }
    }

    private Map<String, String> createResponse(String key, String value) {
        Map<String, String> response = new HashMap<>();
        response.put(key, value);
        return response;
    }
    
    private Map<String, Object> createObjectResponse(String key, Object value) {
        Map<String, Object> response = new HashMap<>();
        response.put(key, value);
        return response;
    }
} 